package cn.jiyun.controller;

import cn.jiyun.face.MyFaceFeature;
import cn.jiyun.pojo.Clock;
import cn.jiyun.pojo.Employees;
import cn.jiyun.pojo.dto.BaseDto;
import cn.jiyun.result.Result;
import cn.jiyun.service.ClockService;
import cn.jiyun.service.EmployeesService;
import cn.jiyun.util.Base64Utils;
import com.arcsoft.face.EngineConfiguration;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FunctionConfiguration;
import com.arcsoft.face.enums.DetectMode;
import com.arcsoft.face.enums.DetectOrient;
import com.arcsoft.face.enums.ErrorInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/face")
@CrossOrigin
public class FaceController {

    // 单例模式的 FaceEngine
    private static FaceEngine faceEngine;

    static {
        File libDir = new File("ruoyi-modules/fase/lib/WIN64").getAbsoluteFile();
        faceEngine = new FaceEngine(libDir.getPath());
        // 引擎配置
        EngineConfiguration engineConfiguration = new EngineConfiguration();
        //检测模式 图片/视频，这里选择的是图片模式
        engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
        //人脸检测角度
        engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_0_ONLY);
        // 功能配置
        FunctionConfiguration functionConfiguration = new FunctionConfiguration();
        //是否支持年龄检测
        functionConfiguration.setSupportAge(true);
        //是否支持3D人脸检测
        functionConfiguration.setSupportFace3dAngle(true);
        //是否支持人脸检测
        functionConfiguration.setSupportFaceDetect(true);
        //是否支持人脸识别
        functionConfiguration.setSupportFaceRecognition(true);
        //是否支持性别检测
        functionConfiguration.setSupportGender(true);
        //是否支持RGB活体检测
        functionConfiguration.setSupportLiveness(true);
        //是否支持RGB活体检测
        functionConfiguration.setSupportIRLiveness(true);
        //设置引擎功能配置
        engineConfiguration.setFunctionConfiguration(functionConfiguration);
        // 初始化引擎
        int initCode = faceEngine.init(engineConfiguration);
        if (initCode != ErrorInfo.MOK.getValue()) {
            System.out.println("初始化引擎失败");
        }
    }

    @Autowired
    private ClockService clockService;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Value("${redis.tokenTime}")
//    private Integer tokenTime;

    // 单例模式的 MyFaceFeature
    private static final MyFaceFeature myFaceFeature = new MyFaceFeature();

    // 添加人脸
    @RequestMapping("/add")
    public Result addFace(@RequestBody BaseDto baseDto, HttpServletRequest request) {
        // 去掉base64编码中的图片头信息
        String base64 = baseDto.getBase().split(",")[0];
        System.out.println(base64);
        String fileName = UUID.randomUUID().toString() + ".jpg";
        try {
            String fullPath = "E://ideaProject/p12/personnel-management-project/ruoyi-modules/ruoyi-fase/img/" + fileName + ".jpg";
            // base64转图片
            Base64Utils.generateImage(base64, fullPath);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("图片转换失败");
        }

        // 获取人脸特征
        byte[] extract = myFaceFeature.extract(new File("E://ideaProject/p12/personnel-management-project/ruoyi-modules/ruoyi-fase/img/" + fileName + ".jpg"), faceEngine);
        if (extract == null) {
            return Result.fail("人脸识别失败");
        }
        baseDto.setBase(base64);
        clockService.updatefase(baseDto);
        return Result.ok();
    }


    // 缓存用户列表
    private List<Clock> userListCache;
    @Autowired
    EmployeesService employeesService;

    // 人脸比对
    @RequestMapping("bidui")
    public Result login(@RequestBody BaseDto base) {
        if (base.getBase() == null) {
            return Result.fail("请上传人脸图片");
        }
        // 去掉base64编码中的图片头信息
        String base64 = base.getBase().split(",")[1];
        String fileName = UUID.randomUUID().toString() + ".jpg";
        String fullPath = "E://ideaProject/p12/personnel-management-project/ruoyi-modules/ruoyi-fase/img/" + fileName + ".jpg";
        try {
            Base64Utils.generateImage(base64, fullPath);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("图片转换失败");
        }
        // 获取当前人脸特征
        byte[] extract = myFaceFeature.extract(new File(fullPath), faceEngine);
        if (extract == null) {
            return Result.fail("提取特征失败");
        }

// 确保 userListCache 不为 null
//        if (userListCache == null) {
//            userListCache = clockService.select();
//        }

// 获取用户信息
        Employees user = clockService.getEmployees(base.getId());

        if (user.getFaseInfo() == null) {
            return Result.ok("nonono");
        }
        System.out.println(user);

// 创建面部特征对比对象,将数据库中员工的特征提取出来
        MyFaceFeature faceContrast = myFaceFeature;
        String filenamea = UUID.randomUUID().toString() + ".jpg";
        String fullPatha = "E://ideaProject/p12/personnel-management-project/ruoyi-modules/ruoyi-fase/img/" + filenamea + ".jpg";
        try {
            //转图片
            Base64Utils.generateImage(user.getFaseInfo(), fullPatha);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("图片转换失败");
        }
        //获取员工人脸信息
        byte[] extract1 = myFaceFeature.extract(new File(fullPatha), faceEngine);


// 进行面部特征对比
        double similarity = faceContrast.contrast(extract, extract1, faceEngine);
        System.out.println(similarity);
        Clock clock = new Clock();
//查找员工外键
        Employees employees = employeesService.getEmployees(base.getId());
// 判断相似度是否大于 0.8
        if (similarity > 0.8) {
            System.out.println("匹配成功");
            clock.setEmployeeId(employees.getName());
            clock.setClockInTime(new Date());
            clock.setClockStatus(1);
            clockService.insert(clock);
            return Result.ok("匹配成功");
        } else {
            return Result.fail("匹配失败");
        }
    }

    @RequestMapping("getEmployees/{id}")
    public Boolean getEmployees(@PathVariable Integer id) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(date);
        //获取当天打卡记录的人
        List<Clock> employees = clockService.getClock(format1);
        //获取他要打卡的人
        Employees clock = clockService.getByidEmployyes(id);
        for (Clock employee : employees) {
            if (employee.getEmployeeId().equals(clock.getName()) ) {
                return false;
            }
        }
        return true;
    }

}
